const userList = [{
	username: 'admin',
	password: 'admin',
	// 角色
	role: 'admin',
	nickname: '管理员',
	avator: 'https://robohash.org/1231231?sets=set3'
}, {
	username: 'zhangsan',
	password: 'zhangsan',
	//角色
	role: 'common',
	nickname: '月入过万的程序员-校长',
	avator: 'https://robohash.org/123?sets=set4'
}]
let { list } = require('./mockjs')
const bodyParser = require('body-parser')
module.exports = app => {

	app.use(bodyParser.json())

	app.post('/api/login', (req, res) => {
		const { username, password } = req.body;
		const user = userList.find(v => v.username === username && v.password === password)
		if (user) {
			res.send({
				code: 200,
				data: {
					username: user.username,
					nickname: user.nickname,
					avator: user.avator,
					token: 'XZXXXXXXXXXXXXXXXXXXXXXXXXXXX',
					role: user.role,
				},
				message: '登录成功， 欢迎' + user.nickname
			})
		} else {
			res.send({
				code: 404,
				message: '登录失败， 请重新登录'
			})
		}
	})

	// 列表请求接口
	app.get('/api/list', (req, res) => {
		res.send({
			code: 200,
			data: list
		})
	})

	// 列表删除接口
	app.delete('/api/list', (req, res) => {
		const { id } = req.query;
		// id 是一个字符串， 可以存在多个id， id和id之间以逗号分隔
		// id => "1234567"
		// id => "1234567, 1231231231, 1231231"
		// 方式一 过滤id
		list = list.filter(v => !id.includes(v.id))
		// 方式二： splice
		// const i = list.findIndex(v => v.id === id)
		// list.splice(i, 1)

		res.send({
			code: 200,
			message: '数据删除成功！！'
		})
	})

	// 更新数据接口
	app.put('/api/list/:id', (req, res) => {
		const { id } = req.params;
		const item = list.find(v => v.id === id);

		Object.assign(item, req.body);
		res.send({
			code: 200,
			message: '数据修改成功！！'
		})
	})


}